package htfile

import (
	"bytes"
	"context"
	"core/coreutil"
	"core/file"
	"core/myerrors"
	"go.mongodb.org/mongo-driver/bson"
	"ht/api/htfile/mongo"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

const (
	URLPrev        = "/htfile"
	COLLName       = "file"
	COLCONVERLName = "fileconver"
	COLPDFName     = "filepdf"
)

type HtfileService struct {
}

// Get  获取数据
func (p *HtfileService) Get(id int64) (*mongo.File, error) {
	var m = &mongo.File{}
	coll := coreutil.MongoUtil.Collection(COLLName)
	filter := bson.D{{"_id", id}}
	err := coll.FindOne(context.TODO(), filter).Decode(m)
	if err != nil {
		return nil, myerrors.NewByCode(myerrors.ERROR_DATANOTEXIST)
	}
	if "" != m.FileId {
		bucket := coreutil.GetGridfsBucket(COLLName)
		fileBuffer := bytes.NewBuffer(nil)
		if _, err = bucket.DownloadToStream(m.FileId, fileBuffer); err != nil {
			return nil, myerrors.NewByErr(err)
		}
		var data = fileBuffer.Bytes()
		m.Data = &data

	}
	return m, nil
}

// 获取封面
func (p *HtfileService) GetCover(id int64) (*[]byte, error) {
	var m = &mongo.FileConvert{}
	coll := coreutil.MongoUtil.Collection(COLCONVERLName)
	filter := bson.D{{"_id", id}}
	err := coll.FindOne(context.TODO(), filter).Decode(m)
	if err != nil {
		//不存在
		return nil, err
	} else {
		return m.Data, nil
	}
	return nil, myerrors.New("系统异常")
}

// 获取预览
func (p *HtfileService) GetShow(id int64) (*mongo.File, error) {
	var r = &mongo.File{}

	var m = &mongo.FileConvert{}
	coll := coreutil.MongoUtil.Collection(COLPDFName)
	filter := bson.D{{"_id", id}}
	err := coll.FindOne(context.TODO(), filter).Decode(m)
	if err != nil {
		//不存在
		mold, err := p.Get(id)
		if err != nil {
			return nil, err
		}
		return mold, nil
	} else {
		r.Data = m.Data
		r.ContentType = "application/pdf"
		return r, nil
	}
	return nil, myerrors.New("系统异常")
}

func (p *HtfileService) GetUrl(id int64) string {
	var Url = file.Config.FixUrl + URLPrev + "/down?id=" + strconv.FormatInt(id, 10)
	return Url
}

func (p *HtfileService) SaveCover(mold *mongo.File) error {
	var m = &mongo.FileConvert{
		Id:   mold.Id,
		Data: nil,
	}
	coll := coreutil.MongoUtil.Collection(COLCONVERLName)

	var ext = file.GetExt(mold.Name)
	if strings.HasPrefix(mold.ContentType, "image") {
		data2, err := file.ImageZoom(*mold.Data, 300, 300)
		if err != nil {
			return err
		}
		m.Data = &data2
		_, err = coll.InsertOne(context.Background(), m)
		if err != nil {
			return err
		}
		return nil
	}

	if ext == "doc" || ext == "docx" || ext == "xls" || ext == "xls" || ext == "ppt" || ext == "pptx" || ext == "pdf" {
		var oldname = filepath.Join(file.Config.Tmp, strconv.FormatInt(m.Id, 10)+"."+ext)
		os.WriteFile(oldname, *mold.Data, 0777)
		var newname = filepath.Join(file.Config.Tmp, strconv.FormatInt(m.Id, 10)+".png")
		var b = file.ConvertToPNG(oldname, newname)
		if !b {
			return myerrors.New("文件转换失败")
		}
		newdata, err := os.ReadFile(newname)
		if err != nil {
			return err
		}
		m.Data = &newdata
		_, err = coll.InsertOne(context.Background(), m)
		if err != nil {
			return err
		}
		return nil
	}
	return nil
}

func (p *HtfileService) SavePdfShow(mold *mongo.File) error {
	var m = &mongo.FileConvert{
		Id:   mold.Id,
		Data: nil,
	}
	coll := coreutil.MongoUtil.Collection(COLPDFName)

	var ext = file.GetExt(mold.Name)
	if ext == "doc" || ext == "docx" || ext == "xls" || ext == "xls" || ext == "ppt" || ext == "pptx" {
		var oldname = filepath.Join(file.Config.Tmp, strconv.FormatInt(m.Id, 10)+"."+ext)
		os.WriteFile(oldname, *mold.Data, 0777)
		var newname = filepath.Join(file.Config.Tmp, strconv.FormatInt(m.Id, 10)+".pdf")
		var b = file.ConvertToPDF(oldname, newname)
		if !b {
			return myerrors.New("文件转换失败")
		}
		newdata, err := os.ReadFile(newname)
		if err != nil {
			return err
		}
		m.Data = &newdata
		_, err = coll.InsertOne(context.Background(), m)
		if err != nil {
			return err
		}
		return nil
	}
	return nil
}
func GetUrl(id int64) string {
	var Url = file.Config.FixUrl + URLPrev + "/down?id=" + strconv.FormatInt(id, 10)
	return Url
}
